package cn.edu.njust.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;

import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@WebServlet(name = "kaptcha", value = "/kaptcha")
public class kaptcha extends HttpServlet {      //验证码
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DefaultKaptcha dk = new DefaultKaptcha();
        InputStream is = getClass().getClassLoader().getResourceAsStream("kaptcha.properties");
        Properties properties = new Properties();
        properties.load(is);
        Config config = new Config(properties);
        dk.setConfig(config);
        String code = dk.createText();
        HttpSession session = request.getSession();
        session.setAttribute("code",code);
        BufferedImage image = dk.createImage(code);
        response.setContentType("image/jpeg");
        boolean jpg = ImageIO.write(image,"jpg", response.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
